/**
 * 京东联盟物料精选商品查询模块
 * @version 1.0.0
 * @author 开发者
 * @see {@link https://union.jd.com/openplatform/api/1230|京东联盟API文档}
 */

const {
  normalizePayload,
  normalizeDbConfig,
  buildSignParams,
  buildJdSign,
  parseJdQueryResult,
  persistDocs,
  JD_API_URL,
  mapRankGoodsDoc,
  mapMergedGoodsDoc,
  chunkArray,
  buildQueryResultMeta
} = require('./@utils')
const queryGoodsBigfield = require('./queryGoodsBigfield')

/**
 * 京东物料精选商品查询接口
 *
 * @param {object} payload 请求参数
 * @param {object} [payload.auth] 认证信息
 * @param {object} payload.query 查询参数
 * @param {number} payload.query.eliteId 频道ID
 * @param {string|number} [payload.query.userId] 用户ID
 * @param {number} [payload.query.pageIndex=1] 页码
 * @param {number} [payload.query.pageSize=20] 每页数量（最大60）
 * @param {number} [payload.query.sortType] 排序类型
 * @param {boolean} [payload.query.includeBigfield=false] 是否补充大字段
 * @param {number} [payload.query.detailSceneId] 详情场景ID
 * @param {number} [payload.query.detailChunkSize=10] 详情查询分块大小
 * @param {object} [payload.options] 可选配置
 * @param {string|object} [payload.options.db] 数据库配置
 * @returns {Promise<{requestParams: object, response: any, queryResult?: object, baseGoods?: any[], detailGoods?: any[], mergedGoods?: any[], dbResult?: any}>}
 * @example
 * // 新格式
 * await queryMaterialGoods({
 *   query: { eliteId: 1, pageSize: 20, includeBigfield: true },
 *   options: { db: 'jd_material_goods' }
 * })
 */
async function queryMaterialGoods(payload) {
  const { auth, query, options } = normalizePayload(payload)

  const {
    goodsReq,
    eliteId,
    userId,
    pageIndex = 1,
    pageSize = 10, // 默认10，也是最大值
    sortType,
    includeBigfield = false,
    detailSceneId,
    detailChunkSize = 10
  } = query

  let finalGoodsReq = goodsReq
  if (!finalGoodsReq) {
    if (typeof eliteId !== 'number') {
      throw new Error('eliteId不能为空')
    }
    finalGoodsReq = {
      eliteId,
      pageIndex,
      pageSize: Math.max(1, Math.min(pageSize, 10)) // 最大10
    }
    if (userId !== undefined && userId !== null && userId !== '') {
      finalGoodsReq.userId = userId
    }
    if (typeof sortType === 'number') {
      finalGoodsReq.sort = sortType
    }
  }

  const { params, appSecret: secret } = buildSignParams({
    appKey: auth.appKey,
    appSecret: auth.appSecret,
    method: 'jd.union.open.goods.material.query',
    businessParams: {
      goodsReq: finalGoodsReq
    },
    timestamp: options.timestamp,
    version: options.version,
    format: options.format,
    signMethod: options.signMethod,
    accessToken: auth.accessToken
  })
  const { sign } = buildJdSign(secret, params)
  const requestParams = {
    ...params,
    sign
  }

  const { status, data } = await uniCloud.httpclient.request(JD_API_URL, {
    method: 'POST',
    data: requestParams,
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded',
    timeout: 10000
  })

  if (status !== 200) {
    throw new Error(`京东联盟接口请求失败，HTTP状态码：${status}`)
  }

  const queryResult = parseJdQueryResult(data, 'jd_union_open_goods_material_query_responce')
  const baseGoods = Array.isArray(queryResult?.data) ? queryResult.data : []

  let detailGoods
  let mergedGoods
  if (includeBigfield && baseGoods.length > 0) {
    const itemIds = baseGoods.map((item) => item.itemId).filter(Boolean)
    const chunkSize = Math.max(1, Math.min(detailChunkSize, 20))
    detailGoods = []
    for (const idsChunk of chunkArray(itemIds, chunkSize)) {
      const goodsReq = {
        itemIds: idsChunk
      }
      if (typeof detailSceneId === 'number') {
        goodsReq.sceneId = detailSceneId
      }
      const res = await queryGoodsBigfield({
        auth,
        query: { goodsReq },
        options: { ...options, db: undefined }
      })
      const chunkDetails = Array.isArray(res.queryResult?.data) ? res.queryResult.data : []
      detailGoods.push(...chunkDetails)
    }
    const detailMap = new Map((detailGoods || []).map((item) => [item.itemId, item]))
    mergedGoods = baseGoods.map((item) => ({
      ...item,
      bigfield: detailMap.get(item.itemId)
    }))
  }
  let dbResult
  const dbConfig = normalizeDbConfig(options.db)
  if (dbConfig) {
    const persistenceList = includeBigfield && mergedGoods ? mergedGoods : baseGoods
    const persistenceTransform =
      includeBigfield && mergedGoods ? mapMergedGoodsDoc : mapRankGoodsDoc
    dbResult = await persistDocs({
      collectionName: dbConfig.collection,
      list: persistenceList,
      transform: persistenceTransform,
      uniqueKeys: dbConfig.uniqueKeys,
      extraDocFields: {
        requestParams,
        queryResultMeta: buildQueryResultMeta(queryResult),
        ...(dbConfig.extraFields || {})
      }
    })
  }

  if (options.debug) {
    return {
      requestParams,
      response: data,
      queryResult,
      baseGoods,
      detailGoods,
      mergedGoods,
      dbResult
    }
  }

  // 如果包含大字段，返回合并后的数据
  if (includeBigfield && mergedGoods) {
    return {
      ...queryResult,
      data: mergedGoods
    }
  }

  return queryResult
}

module.exports = queryMaterialGoods
